package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.Constants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateTimeZoneConverter;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import io.netty.util.internal.UnstableApi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.web.bind.annotation.RequestBody;

/**
 * 设备表Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-08-01
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private IoTDAClient client;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询设备表
     * 
     * @param id 设备表主键
     * @return 设备表
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备表列表
     * 
     * @param device 设备表
     * @return 设备表
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备表
     * 
     * @param device 设备表
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {
        return save(device) ? 1 : 0;
    }

    /**
     * 修改设备表
     * 
     * @param device 设备表
     * @return 结果
     */
    @Override
    public int updateDevice(Device device)
    {
        return updateById(device) ? 1 : 0;
    }

    /**
     * 批量删除设备表
     * 
     * @param ids 需要删除的设备表主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备表信息
     * 
     * @param id 设备表主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 同步产品列表
     */
    @Override
    public void syncProductList() {
        //查询产品列表
        ListProductsRequest request=new ListProductsRequest();
        request.setLimit(50);
        ListProductsResponse response = client.listProducts(request);
        if (response.getHttpStatusCode()!=200) {
            throw new BaseException("同步产品列表失败");
        }
        List<ProductSummary> products = response.getProducts();
        //保存到redis中一份
        redisTemplate.opsForValue().set(Constants.IOT_ALL_PRODUCT_LIST, JSONUtil.toJsonStr(products));
    }

    /**
     * 查询产品列表
     *
     * @return
     */
    @Override
    public List<ProductVo> allProduct() {
        String productStr = (String) redisTemplate.opsForValue().get(Constants.IOT_ALL_PRODUCT_LIST);
        if (StrUtil.isEmpty(productStr)) {
            return Collections.emptyList();
        }
        return JSONUtil.toList(productStr, ProductVo.class);
    }

    /**
     * 注册设备
     *
     * @param dto
     */
    @Override
    public void registerDevice(DeviceDto dto) {
        //1.查询设备名称是否重复
        long count = this.count(Wrappers.<Device>lambdaQuery().eq(Device::getDeviceName, dto.getDeviceName()));
        if (count>0) {
            throw new BaseException("设备名称重复");
        }
        //2.查询设备标识是否重复
        count= this.count(Wrappers.<Device>lambdaQuery().eq(Device::getNodeId, dto.getNodeId()));
        if (count>0) {
            throw new BaseException("设备标识重复");
        }

        //3.同一位置是否绑定了相同的产品
        count= this.count(Wrappers.<Device>lambdaQuery()
                .eq(Device::getProductKey, dto.getProductKey())//产品key
                .eq(Device::getBindingLocation, dto.getBindingLocation())//绑定位置
                .eq(Device::getLocationType, dto.getLocationType())//位置类型
                .eq(dto.getPhysicalLocationType()!=null,Device::getPhysicalLocationType, dto.getPhysicalLocationType())//物理位置类型
        );
        if (count>0){
            throw new BaseException("同一位置已绑定相同产品");
        }

        //4.注册设备到IOT平台
        AddDeviceRequest request=new AddDeviceRequest();
        AddDevice body=new AddDevice();
        body.setNodeId(dto.getNodeId());
        body.setProductId(dto.getProductKey());
        body.setDeviceName(dto.getDeviceName());

        AuthInfo authInfo=new AuthInfo();

        String secret = UUID.randomUUID().toString().replaceAll("-", "");
        authInfo.setSecret(secret);
        body.setAuthInfo(authInfo);
        
        request.setBody(body);

        AddDeviceResponse response = client.addDevice(request);
        if (response.getHttpStatusCode()!=201) {
            throw new BaseException("设备注册失败");
        }

        //5.保存设备信息到本地数据库表中
        Device device= BeanUtil.toBean(dto, Device.class);
        device.setBindingLocation(String.valueOf(dto.getBindingLocation()));
        device.setIotId(response.getDeviceId());
        device.setSecret(secret);
        this.save(device);
    }

    /**
     * 查询设备详情
     *
     * @param iotId
     * @return
     */
    @Override
    public DeviceDetailVo queryDeviceDetail(String iotId) {
        //3.查询本地数据库
        Device device = this.getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
        if (ObjectUtil.isEmpty(device)) {
            throw new BaseException("设备不存在");
        }

        //2.查询物联网平台IOT
        ShowDeviceRequest request=new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse response = client.showDevice(request);
        if (response.getHttpStatusCode()!=200) {
            throw new BaseException("查询设备详情失败");
        }
        String status = response.getStatus();//设备状态
        String activeTimeStr = response.getActiveTime();//激活时间

        //1.封装数据
        DeviceDetailVo vo=BeanUtil.toBean(device, DeviceDetailVo.class);
        vo.setBindingLocation(Long.valueOf(device.getBindingLocation()));
        vo.setDeviceStatus(status);
        //转化日期类型
        if (StringUtils.isNotEmpty(activeTimeStr)) {
            LocalDateTime activeTime = LocalDateTimeUtil.parse(activeTimeStr, DatePattern.UTC_MS_PATTERN);
            activeTime=DateTimeZoneConverter.utcToShanghai(activeTime);
            vo.setActiveTime(activeTime);
        }
        return vo;
    }

    /**
     * 查询设备的上报数据
     *
     * @param iotId
     * @return
     */
    @Override
    public List<Map<String, Object>> queryServiceProperties(String iotId) {
        //1.查询IOT平台上的设备数据
        ShowDeviceShadowRequest request=new ShowDeviceShadowRequest();
        request.setDeviceId(iotId);
        ShowDeviceShadowResponse response = client.showDeviceShadow(request);
        if (response.getHttpStatusCode()!=200) {
            throw new BaseException("查询设备影子数据失败");
        }
        //1.1.获取上报数据集合
        List<DeviceShadowData> shadowList = response.getShadow();
        if (CollectionUtil.isEmpty(shadowList)) {
            return Collections.emptyList();
        }
        //1.2 上报数据的属性对象
        DeviceShadowProperties deviceShadowProperties = shadowList.get(0).getReported();
        //1.3 获取属性对象，json对象
        Object properties1 = deviceShadowProperties.getProperties();
        JSONObject jsonObject = JSONUtil.parseObj(properties1);

        //1.4 获取设备上报时间
        String eventTimeStr = deviceShadowProperties.getEventTime();
        LocalDateTime eventTimeLocalDateTime = LocalDateTimeUtil.parse(eventTimeStr, "yyyyMMdd'T'HHmmss'Z'");
        // 时区转换
        LocalDateTime eventTime = DateTimeZoneConverter.utcToShanghai(eventTimeLocalDateTime);


        //2.封装数据并返回
        List<Map<String, Object>> list=new ArrayList<>();
        //2.1 遍历属性对象，key表示属性名称，value表示属性值
        jsonObject.forEach((key, value)->{
            Map<String, Object> map=new HashMap<>();
            map.put("functionId", key);
            map.put("value", value);
            map.put("eventTime", eventTime);
            list.add(map);
        });

        return list;
    }

    /**
     * 查询产品详情数据
     *
     * @param productkey
     * @return
     */
    @Override
    public List<ServiceCapability> queryProduct(String productkey) {
        if (StrUtil.isEmpty(productkey)) {
            throw new BaseException("产品key不能为空");
        }
        //1.调用IOT平台查询产品详情数据
        ShowProductRequest request=new ShowProductRequest();
        request.setProductId(productkey);
        ShowProductResponse response = client.showProduct(request);

        if (response.getHttpStatusCode()!=200) {
            return Collections.emptyList();
        }
        List<ServiceCapability> serviceCapabilities = response.getServiceCapabilities();
        if (CollectionUtil.isEmpty(serviceCapabilities)) {
            return Collections.emptyList();
        }
        return serviceCapabilities;
    }
}
